package com.sch.www.ele.controller;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.sch.www.common.base.ResultBean;
import com.sch.www.common.core.web.BaseController;
import com.sch.www.common.validator.NotBlankFluentValidator;
import com.sch.www.ele.entity.Region;
import com.sch.www.ele.services.RegionServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("v1/region")
@RestController
public class RegionController extends BaseController {


    @Autowired
    RegionServices regionServices;

    @RequestMapping(value = "listByPid")
    private ResultBean<List<Region>> listByPid(String pid) {
        ResultBean<List<Region>> resultBean = ResultBean.newInstance();
        List<Region> regionList = regionServices.listByPid(pid);
        return resultBean.setData(regionList);
    }


    @PostMapping("add")
    public ResultBean<Region> add(@RequestBody Region region) {
        ResultBean<Region> resultBean = ResultBean.newInstance();
        ComplexResult complexResult = FluentValidator.checkAll().failOver()
                .on(region.getCode(), new NotBlankFluentValidator("code"))
                .on(region.getName(), new NotBlankFluentValidator("name"))
                .on(region.getPid(), new NotBlankFluentValidator("pid"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!complexResult.isSuccess()) {
            return resultBean.setError().appendMsg(complexResult);
        }
        regionServices.insertSelective(region.getCode(), region.getName(), region.getPid());
        return resultBean;
    }

    @PostMapping("modify")
    public ResultBean<Region> modify(@RequestBody Region region) {
        ResultBean<Region> resultBean = ResultBean.newInstance();
        ComplexResult complexResult = FluentValidator.checkAll().failOver()
                .on(region.getId(), new NotBlankFluentValidator("id"))
                .on(region.getCode(), new NotBlankFluentValidator("code"))
                .on(region.getName(), new NotBlankFluentValidator("name"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!complexResult.isSuccess()) {
            return resultBean.setError().appendMsg(complexResult);
        }
        regionServices.updateByIdSelective(region.getId(), region.getCode(), region.getName());
        return resultBean;
    }


}
